package com.matt.foundation.utils.export;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.block.BlockBorder;
import org.jfree.data.category.DefaultCategoryDataset;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Vector;

/**
 *
 * @author ccw
 * @date 2014-6-11
 *       <p>
 *       创建图表步骤：<br/>
 *       1：创建数据集合<br/>
 *       2：创建Chart：<br/>
 *       3:设置抗锯齿，防止字体显示不清楚<br/>
 *       4:对柱子进行渲染，<br/>
 *       5:对其他部分进行渲染<br/>
 *       6:使用chartPanel接收<br/>
 *
 *       </p>
 */
public class BarChart {
	public BarChart() {
	}

	private static DefaultCategoryDataset createDataset(String[] categories, Double[] values, String childrenName) {
		// 标注类别
		Vector<Serie> series = new Vector<Serie>();
		// 柱子名称：柱子所有的值集合
		series.add(new Serie(childrenName, values));
		// 1：创建数据集合
		DefaultCategoryDataset dataset = ChartUtils.createDefaultCategoryDataset(series, categories);
		return dataset;
	}

	private static JFreeChart createChart(String[] categories, Double[] values, String childrenName) {
		// 2：创建Chart
		JFreeChart chart = ChartFactory.createBarChart("注：<85分弱势；85-115分正常；115-130分中等偏上；>130分优势",
				"", "得分", createDataset(categories, values, childrenName));
		// 3:设置抗锯齿，防止字体显示不清楚
		ChartUtils.setAntiAlias(chart);// 抗锯齿
		// 4:对柱子进行渲染
		ChartUtils.setBarRenderer(chart.getCategoryPlot(), false);//
		// 5:对其他部分进行渲染
		ChartUtils.setXAixs(chart.getCategoryPlot());// X坐标轴渲染
		ChartUtils.setYAixs(chart.getCategoryPlot());// Y坐标轴渲染

		//额外设置
		chart.getCategoryPlot().getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);

		// 设置标注无边框
		chart.getLegend().setFrame(new BlockBorder(Color.WHITE));

		return chart;
	}

	public static BufferedImage createChartBufferedImage(String[] categories, Double[] values, String childrenName){
		JFreeChart chart = createChart(categories, values, childrenName);

		//输出文件
		BufferedImage image = new BufferedImage(875, 400, BufferedImage.TYPE_INT_ARGB);
		Graphics2D g2 = image.createGraphics();

		g2.setRenderingHint(JFreeChart.KEY_SUPPRESS_SHADOW_GENERATION, true);
		Rectangle r = new Rectangle(0, 0, 875, 400);
		chart.draw(g2, r);

		return image;
	}

}
